package com.jeesite.modules.sd.common.task;

import com.jeesite.common.config.Global;
import com.jeesite.common.lang.ObjectUtils;
import com.jeesite.modules.sd.common.constants.GlobalEnum;
import com.jeesite.modules.sd.common.constants.MsgTypeEnum;
import com.jeesite.modules.sd.entity.DocDeliverRecord;
import com.jeesite.modules.sd.entity.DocRecv;
import com.jeesite.modules.sd.entity.MsgManager;
import com.jeesite.modules.sd.service.DocDeliverRecordService;
import com.jeesite.common.lang.DateUtils;
import com.jeesite.modules.sd.service.DocRecvService;
import com.jeesite.modules.sd.service.MsgManagerService;
import com.jeesite.modules.sys.entity.EmpUser;
import com.jeesite.modules.sys.entity.Office;
import com.jeesite.modules.sys.entity.User;
import com.jeesite.modules.sys.service.EmpUserService;
import com.jeesite.modules.sys.service.OfficeService;
import com.jeesite.modules.sys.service.UserService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Configuration
@EnableScheduling
public class UrgeFile {
    @Autowired
    private DocDeliverRecordService recordService;
    @Autowired
    private DocRecvService docRecvService;
    @Autowired
    private EmpUserService empUserService;
    @Autowired
    private OfficeService officeService;
    @Autowired
    private UserService userService;
    @Autowired
    private MsgManagerService msgManagerService;
    /**
     * 催领
     * 每天8点执行一次 0 0 8 * * ?
     */
  @Scheduled(cron = "0 0 8 * * ?")
    public void urgeTakeFile(){
      List<DocDeliverRecord> docDeliverRecords = recordService.listOutTimeTakeRecord();
      Map<String, List<DocDeliverRecord>> recordsMap= docDeliverRecords.stream().collect(Collectors.groupingBy(DocDeliverRecord::getDeliverType));
      boolean send = recordsMap.containsKey(GlobalEnum.RECORD_DELIVER_TYPE_SEND.getKey());
      boolean take = recordsMap.containsKey(GlobalEnum.RECORD_DELIVER_TYPE_DELIVER.getKey());
      List<DocDeliverRecord> docDeliverRecords1 = recordsMap.get(GlobalEnum.RECORD_DELIVER_TYPE_DELIVER.getKey());
      List<DocDeliverRecord> sendRecords = recordsMap.get(GlobalEnum.RECORD_DELIVER_TYPE_SEND.getKey());
      String nowTime= DateUtils.formatDate(new Date(),"yyyy-MM-dd");
     //送文单位
      if(send){
          User secretariatUser = recordService.getSecretariatUser();
          if (ObjectUtils.isEmpty(secretariatUser)){
               throw  new RuntimeException("秘书处没有人");
          }
          String phone=secretariatUser.getMobile();
          if(CollectionUtils.isNotEmpty(sendRecords)){
              sendRecords.forEach(sendRecord->{
                  Date getBeforeTakeDate = sendRecord.getBeforeTakeDate();
                  Date date =DateUtils.addDays(getBeforeTakeDate, Global.getConfigToInteger("doc.msg.urgeTakeDay", "3"));
                  String str=  DateUtils.formatDate(getBeforeTakeDate,"yyyy-MM-dd");
                  if (str.equals(nowTime)){

                  Office office = officeService.get(sendRecord.getRecvUnitCode());
                  DocRecv docRecv = docRecvService.get(sendRecord.getDocId());
                  MsgManager msgManager=new MsgManager();
              msgManager.setTelphone(phone);
              msgManager.setSendDate(new Date());
              msgManager.setMsgType(MsgTypeEnum.MSG_TYPE_TAKE.getKey());
              msgManager.setSendStatus(MsgTypeEnum.MSG_TYPE_STATE_FAIL.getKey());
              msgManager.setDocId(sendRecord.getId());
              msgManager.setMsgContent(office.getOfficeName()+" 有一份文件超时未领取《"+docRecv.getDocTitle()+"》,请及时领取。");
               msgManagerService.save(msgManager);
               //修改文件日期
                      System.out.printf("id="+sendRecord.getId());
                      sendRecord.setBeforeTakeDate(date);
                      recordService.save(sendRecord);
                  }

              });
          }

      }

      //领文单位
      if (take){
     if (CollectionUtils.isNotEmpty(docDeliverRecords1)){
         docDeliverRecords1.forEach(docDeliverRecord -> {
             MsgManager msgManager=new MsgManager();
             Date getBeforeTakeDate = docDeliverRecord.getBeforeTakeDate();
             Date date =DateUtils.addDays(getBeforeTakeDate, Global.getConfigToInteger("doc.msg.urgeTakeDay", "3"));
              String str=  DateUtils.formatDate(getBeforeTakeDate,"yyyy-MM-dd");

              String st=docDeliverRecord.getId();
             String unitCode;
             EmpUser empUser1;
             if(str.equals(nowTime)){
                 DocRecv docRecv1 = docRecvService.get(docDeliverRecord.getDocId());
                 unitCode= docDeliverRecord.getRecvUnitCode();
                 empUser1 = new EmpUser();
                 empUser1.setCodes(new String[]{unitCode});
                 List<EmpUser> users = empUserService.findUserListByOfficeCodes(empUser1);
                 if (CollectionUtils.isEmpty(users)) {
                     Office office2 = officeService.get(unitCode);
                     throw new RuntimeException(office2.getOfficeName() + "单位没有人");
                 }
                 String userCode = users.get(0).getUserCode();
                 User user = userService.get(userCode);
                 msgManager.setDocId(st);
                 msgManager.setMsgType(MsgTypeEnum.MSG_TYPE_TAKE.getKey());
                 msgManager.setSendStatus(MsgTypeEnum.MSG_TYPE_STATE_FAIL.getKey());
                 msgManager.setMsgContent("您有一份文件超时未领取:《"+docRecv1.getDocTitle()+"》,请及时领取。");
                 msgManager.setSendDate(new Date());
                 msgManager.setTelphone(user.getMobile());
                  //插入数据库一条短信
                  msgManagerService.save(msgManager);
                  //修改文件截止日期
                 System.out.printf("id="+docDeliverRecord.getId());
                  docDeliverRecord.setBeforeTakeDate(date);
                  recordService.save(docDeliverRecord);
             }


         });
     }}

  }

    /**
     * 催还 每天8点
     */
    @Scheduled(cron = "0 0 8 * * ?")
    public void urgeReturnFile(){
        List<DocDeliverRecord> docDeliverRecords = recordService.listOutTimeReturnRecord();

        Map<String, List<DocDeliverRecord>> collect = docDeliverRecords.stream().collect(Collectors.groupingBy(DocDeliverRecord::getDeliverType));

        boolean send = collect.containsKey(GlobalEnum.RECORD_DELIVER_TYPE_SEND.getKey());
        boolean take = collect.containsKey(GlobalEnum.RECORD_DELIVER_TYPE_DELIVER.getKey());
        List<DocDeliverRecord> docDeliverRecords1 = collect.get(GlobalEnum.RECORD_DELIVER_TYPE_DELIVER.getKey());
        List<DocDeliverRecord> sendRecords = collect.get(GlobalEnum.RECORD_DELIVER_TYPE_SEND.getKey());
        String nowTime= DateUtils.formatDate(new Date(),"yyyy-MM-dd");

        //送文单位
        if(send){
            User secretariatUser = recordService.getSecretariatUser();
            if (ObjectUtils.isEmpty(secretariatUser)){
                throw  new RuntimeException("秘书处没有人");
            }
            String phone=secretariatUser.getMobile();
            if(CollectionUtils.isNotEmpty(sendRecords)){
                sendRecords.forEach(sendRecord->{
                    Date getBeforeReturnDate = sendRecord.getBeforeReturnDate();
                    Date date =DateUtils.addDays(getBeforeReturnDate, Global.getConfigToInteger("doc.msg.urgeReturnDay", "3"));
                    String str=  DateUtils.formatDate(getBeforeReturnDate,"yyyy-MM-dd");
                    if (str.equals(nowTime)){

                        Office office = officeService.get(sendRecord.getRecvUnitCode());
                        DocRecv docRecv = docRecvService.get(sendRecord.getDocId());
                        MsgManager msgManager=new MsgManager();
                        msgManager.setTelphone(phone);
                        msgManager.setSendDate(new Date());
                        msgManager.setMsgType(MsgTypeEnum.MSG_TYPE_RETURN.getKey());
                        msgManager.setSendStatus(MsgTypeEnum.MSG_TYPE_STATE_FAIL.getKey());
                        msgManager.setDocId(sendRecord.getId());
                        msgManager.setMsgContent(office.getOfficeName()+"有一份文件超时未归还:《"+docRecv.getDocTitle()+"》,请及时归还。");
                        msgManagerService.save(msgManager);
                        //修改文件日期
                        System.out.printf("id="+sendRecord.getId());
                        sendRecord.setBeforeReturnDate(date);
                        recordService.save(sendRecord);
                    }

                });
            }

        }

        //领文单位
        if (take){
            if (CollectionUtils.isNotEmpty(docDeliverRecords1)){
                docDeliverRecords1.forEach(docDeliverRecord -> {
                    MsgManager msgManager=new MsgManager();
                    Date getBeforeReturnDate = docDeliverRecord.getBeforeReturnDate();
                    Date date =DateUtils.addDays(getBeforeReturnDate, Global.getConfigToInteger("doc.msg.urgeReturnDay", "3"));
                    String str=  DateUtils.formatDate(getBeforeReturnDate,"yyyy-MM-dd");

                    String st=docDeliverRecord.getId();
                    String unitCode;
                    EmpUser empUser1;
                    if(str.equals(nowTime)){
                        DocRecv docRecv1 = docRecvService.get(docDeliverRecord.getDocId());
                        unitCode= docDeliverRecord.getRecvUnitCode();
                        empUser1 = new EmpUser();
                        empUser1.setCodes(new String[]{unitCode});
                        List<EmpUser> users = empUserService.findUserListByOfficeCodes(empUser1);
                        if (CollectionUtils.isEmpty(users)) {
                            Office office2 = officeService.get(unitCode);
                            throw new RuntimeException(office2.getOfficeName() + "单位没有人");
                        }
                        String userCode = users.get(0).getUserCode();
                        User user = userService.get(userCode);
                        msgManager.setDocId(st);
                        msgManager.setMsgType(MsgTypeEnum.MSG_TYPE_RETURN.getKey());
                        msgManager.setSendStatus(MsgTypeEnum.MSG_TYPE_STATE_FAIL.getKey());
                        msgManager.setMsgContent("您有一份文件超时未归还:《"+docRecv1.getDocTitle()+"》,请及时归还。");
                        msgManager.setSendDate(new Date());
                        msgManager.setTelphone(user.getMobile());
                        //插入数据库一条短信
                        msgManagerService.save(msgManager);
                        //修改文件截止日期
                        System.out.printf("id="+docDeliverRecord.getId());
                        docDeliverRecord.setBeforeReturnDate(date);
                        recordService.save(docDeliverRecord);
                    }


                });
            }}


    }

}
